'use strict';

const axios = require('axios');
const uuid = require('uuid/v4');

exports = module.exports = (options) => {
  let logger = Object.assign({}, options.logger);
  delete options.logger;
  let instanceConfig = Object.assign({
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }
  }, options);

  let instance = axios.create(instanceConfig);

  // Add a request interceptor
  instance.interceptors.request.use(function(config) {
    // Do something before request is sent
    let traceId = uuid();
    let method = config.method.toUpperCase();
    let params = config.params || '';
    let data = config.data && JSON.stringify(config.data) || '';

    // append userId to traceId
    if (config.data && config.data.userId) {
      traceId += '-' + config.data.userId;
    }

    config.headers.TraceId = traceId;

    logger && logger.info(method, config.url, traceId, params, data);

    return config;
  }, function(error) {
    // Do something with request error
    return Promise.reject(error);
  });

  // Add a response interceptor
  instance.interceptors.response.use(function(response) {
    // Do something with response data
    let traceId = response.config.headers.TraceId;
    let data = JSON.stringify(response.data);

    logger && logger.info(traceId, data);

    return response;
  }, function(error) {
    // Do something with response error
    let config = error.config;
    let method = config.method.toUpperCase();
    let traceId = config.headers.TraceId;
    let params = config.params || '';
    let data = config.data || '';
    let status = error.response && error.response.status || '';

    logger && logger.error(method, config.url, traceId, params, data, status, error.message);

    return Promise.reject(error);
  });

  return instance;
};